package com.dys.hejiayuncommunity.web.controller.system;

import com.dys.hejiayuncommunity.common.constant.UserConstants;
import com.dys.hejiayuncommunity.common.core.controller.BaseController;
import com.dys.hejiayuncommunity.common.core.domain.BaseResponse;
import com.dys.hejiayuncommunity.common.core.page.PageResult;
import com.dys.hejiayuncommunity.common.utils.ChainedMap;
import com.dys.hejiayuncommunity.common.utils.SecurityUtils;
import com.dys.hejiayuncommunity.system.domain.SysRole;
import com.dys.hejiayuncommunity.system.domain.SysUser;
import com.dys.hejiayuncommunity.system.service.SysPostService;
import com.dys.hejiayuncommunity.system.service.SysRoleService;
import com.dys.hejiayuncommunity.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: 疾风
 * @ClassName: SysUserController
 * @Description: 用户信息
 * @CreateDate: 2024/12/30
 * @Version: v1.0.0
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysPostService postService;

    /**
     * 分页获取用户列表(带条件)
     *
     * @param sysUser 用户信息
     * @return 用户列表
     */
    @GetMapping(value = {"/list"})
    public PageResult list(SysUser sysUser) {
        super.startPage();
        List<SysUser> list = sysUserService.selectUserList(sysUser);
        return super.getData(list);
    }

    /**
     * 删除用户信息
     */
    @DeleteMapping("/{userIds}")
    public BaseResponse remove(@PathVariable Long[] userIds) {
        return super.toAjax(sysUserService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PutMapping(value = {"/resetPwd"})
    public BaseResponse resetPwd(@RequestBody SysUser sysUser) {
        sysUserService.checkEmailUnique(sysUser);
        sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
        sysUser.setUpdateBy(SecurityUtils.getUserName());
        return super.toAjax(sysUserService.resetPwd(sysUser));
    }

    /**
     * 修改状态
     */
    @PutMapping(value = {"/changeStatus"})
    public BaseResponse changeStatus(@RequestBody SysUser user) {
        sysUserService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUserName());
        return super.toAjax(sysUserService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取用户详情
     *
     * @param userId 用户编号
     * @return 用户信息
     */
    @GetMapping(value = {"/", "/{userId}"})
    public ChainedMap getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        ChainedMap map = ChainedMap.create().set("code", 200).set("msg", "操作成功");
        // 获取角色列表
        List<SysRole> roleList = roleService.selectRoleAll();
        // 给用户关联角色信息
        if (SysUser.isAdmin(userId)) {
            // 是admin
            map.put("roles", roleList);
        } else {
            List<SysRole> collect = roleList.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList());
            map.put("roles", collect);
        }
        // 给用户关联岗位信息
        map.put("posts", postService.selectPostAll());

        // userId非空,则执行修改操作
        if (userId != null) {
            map.put("data", sysUserService.selectUserById(userId));
            map.put("postIds", postService.selectPostListByUserId(userId));
            map.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return map;
    }

    /**
     * 添加用户
     *
     * @param user 用户信息
     * @return 响应结果
     */
    @PostMapping
    public BaseResponse add(@RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(sysUserService.checkUserNameUnique(user.getUserName()))) {
            return BaseResponse.failed("新增用户失败," + user.getUserName() + "已经存在");
        } else if (UserConstants.NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(user))) {
            return BaseResponse.failed("新增用户失败," + user.getPhonenumber() + "已经存在");
        } else if (UserConstants.NOT_UNIQUE.equals(sysUserService.checkEmailUnique(user))) {
            return BaseResponse.failed("新增用户失败," + user.getEmail() + "已经存在");
        }
        user.setUpdateBy(SecurityUtils.getUserName());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return super.toAjax(sysUserService.insertUser(user));
    }

    @PutMapping(value = {"/edit"})
    public BaseResponse edit(@RequestBody SysUser user) {
        // 校验用户是否允许操作
        sysUserService.checkUserAllowed(user);
        if (UserConstants.NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(user))) {
            return BaseResponse.failed("修改用户失败," + user.getPhonenumber() + "已经存在");
        } else if (UserConstants.NOT_UNIQUE.equals(sysUserService.checkEmailUnique(user))) {
            return BaseResponse.failed("修改用户失败," + user.getEmail() + "已经存在");
        }
        user.setUpdateBy(SecurityUtils.getUserName());
        return super.toAjax(sysUserService.updateUser(user));
    }
}
